package com.example.zhihu.service;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.example.zhihu.entity.HotData;
import com.example.zhihu.entity.HotData.DataDTO;
import com.example.zhihu.entity.HotDataWeek;
import com.example.zhihu.entity.HotInfo;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @author t-zhaoheng
 * @since 2022/5/5
 */
@Service
public class HotDataService {

  @Value(value = "${zhihu.hot-data.url}")
  String hotDataUrl;

  /**
   * 爬取知乎热榜
   *
   * @return
   */
  public List<DataDTO> getDataDTO() {
    // 获取知乎热榜
    String body = HttpRequest.get(hotDataUrl).execute().body();
    // 解析热榜数据
    HotData hotData = JSONObject.parseObject(body, HotData.class);
    List<DataDTO> dataDTOS = hotData.getData();
    return dataDTOS;
  }

  /**
   * 转化为 HotInfo 对象
   *
   * @param dataDTO
   * @return
   */
  public HotInfo convert2HotInfo(DataDTO dataDTO) {
    HotInfo hotInfo = new HotInfo();
    hotInfo.setInfoId(dataDTO.getTarget().getId().toString());
    hotInfo.setAnswerCount(dataDTO.getTarget().getAnswerCount());
    // 知乎的时间是秒数，不是毫秒数
    hotInfo.setCreated(LocalDateTimeUtil.of(dataDTO.getTarget().getCreated() * 1000));
    hotInfo.setCommentCount(dataDTO.getTarget().getCommentCount());
    hotInfo.setTitle(dataDTO.getTarget().getTitle());
    hotInfo.setFollowerCount(dataDTO.getTarget().getFollowerCount());
    hotInfo.setUrl("https://www.zhihu.com/question/" + dataDTO.getTarget().getId());
    hotInfo.setExcerpt(dataDTO.getTarget().getExcerpt());
    String[] s = dataDTO.getDetailText().split(" ");
    hotInfo.setHotIndex(Integer.parseInt(s[0]));
    // 设置关键词
    List<String> keywordList = new ArrayList<>();
    hotInfo.setKeyword(StrUtil.join(",", keywordList));
    hotInfo.setInsertTime(LocalDateTime.now());
    return hotInfo;
  }
}
